<?php

namespace app\api\service;

use addons\xyb\XypHelper;

use \app\common\model\assistant\Activity as ActivityModel;
use \app\common\model\assistant\Progress as progressModel;
use \app\common\model\assistant\Jobs as jobsModel;
use app\common\model\daily\UsersModel;
use app\common\model\marketing\MarketingCoupons;
use app\common\model\marketing\UsersMarketingCoupons;
use think\Db;

class AssistantService
{
    /*查询用户可参与的*/
    public static function retrieveUsersOngoingTasks($user_id, $circle_id = 0)
    {
        $field = 'id,activity_id,jobs_id,user_id,grant_status,deadline_time';
        $progress = progressModel::field($field)->where('user_id', $user_id)->where('progress_type', 1)
            ->order('id', 'desc')->find();
        if (!$progress) {
            /*获取用户可参加的活动*/
            return self::retrieveUsersFirstParticipateActivity($user_id, $circle_id);
        }
        /*获取活动详情*/
        if (!$activity = self::getUsersParticipateActivity($progress->activity_id, $user_id, $circle_id)) {
            return self::retrieveUsersFirstParticipateActivity($user_id, $circle_id);
        }
        /*获取任务详情*/
        if (!$jobs = jobsModel::getJobsInfo($progress->jobs_id)) {
            return self::retrieveUsersFirstParticipateActivity($user_id, $circle_id);
        }
        $activity->activity_status = 1;
        $activity->next_jobs_id = 0;
        $activity->self_reward = [];
        $activity->inviter_reward = [];
        /*进行中*/
        if ($progress->grant_status == 1) {
            if ((time() > $progress->deadline_time)) {
                $activity->activity_status = 3;
            }
        } /*已完成*/
        elseif ($progress->grant_status == 2) {
            if ($activity->upgrade == 2) {
                if ($next_jobs = jobsModel::getNextJobsInfoByActivity($progress->activity_id, $progress->jobs_id)) {
                    $activity->next_jobs_id = $next_jobs->id;
                }
            } else {
                $activity->activity_status = 0;
            }
        } elseif ($progress->grant_status == 3) {
            if ($activity->is_restart == 1) {
                $activity->activity_status = 0;
            }
        }
        $activity->self_reward = [
            'type' => $jobs->reward_method,
            'point' => $jobs->reward_method == 1 ? (int)$jobs->reward_point : 0,
            'youth' => $jobs->reward_method == 2 ? $jobs->youth_point : 0,
            'coupons' => MarketingCoupons::getAssociationCouponsOneArray($jobs->reward_coupons_id)
        ];
        $activity->inviter_reward = [
            'type' => $jobs->fu_reward_method,
            'point' => $jobs->fu_reward_method == 1 ? (int)$jobs->fu_reward_point : 0,
            'youth' => $jobs->fu_reward_method == 2 ? $jobs->fu_youth_point : 0,
            'coupons' => MarketingCoupons::getAssociationCouponsOneArray($jobs->fu_reward_coupons_id)
        ];
        $activity->is_restart = (int)$activity->restart;
        $activity->is_upgrade = (int)$activity->upgrade;
        $activity->grant_status = $progress->grant_status;
        $activity->current_jobs_id = (int)$jobs->id;
        $activity->grant_total = (int)$jobs->grant_total;
        $activity->days_num = (int)$jobs->days_num;
        $activity->users_method = (int)$jobs->users_method;
        $activity->deadline_time = ($progress->deadline_time - time());
        $activity->progress_id = $progress->id;
        $activity->share_img = cdnurl($activity->share_img);
        /*获取参与人数*/
        $activity->help_users_list = progressModel::getParticipateUsersList($progress->id, $activity->grant_total);
        $activity->help_users_total = progressModel::where('progress_id', $progress->id)->where('progress_type',2)->count();
        return $activity;
    }

    /*用户参与活动报名*/
    public static function userRegistrationParticipate($user_id, $circle_id, $jobs_id)
    {
        if (!$jobs = jobsModel::getJobsInfo($jobs_id)) {
            return ['code' => 0, 'msg' => '任务不存在'];
        }
        /*获取活动详情*/
        if (!$activity = self::getUsersParticipateActivity($jobs->activity_id, $user_id, $circle_id)) {
            return ['code' => 0, 'msg' => '无法参与活动'];
        }
        /*查询用户是否有在进行中的任务*/
        $field = 'id,activity_id,jobs_id,user_id,grant_status,deadline_time';
        $progress = progressModel::field($field)->where('user_id', $user_id)->where('progress_type', 1)
            ->order('id', 'desc')->find();
        if (!$progress) {
            $res = progressModel::userRegistrationParticipate($user_id, $jobs);
            if (!$res || !isset($res->id) || !$res->id) {
                return ['code' => 0, 'msg' => '系统繁忙，请稍后再试'];
            }
            jobsModel::where('id', $jobs_id)->setInc('total_users');
            jobsModel::where('id', $jobs_id)->setInc('progress_total');
            return ['code' => 1, 'msg' => '参与成功', 'data' => $res->id];
        }
        if ((int)$progress->grant_status === 1) {
            return ['code' => 0, 'msg' => '您有正在进行中的任务，请先完成再参与'];
        }
        $progress = progressModel::field($field)->where('user_id', $user_id)->where('progress_type', 1)
            ->where('activity_id', $jobs->activity_id)->order('id', 'desc')->find();
        if (!$progress) {
            $res = progressModel::userRegistrationParticipate($user_id, $jobs);
            if (!$res || !isset($res->id) || !$res->id) {
                return ['code' => 0, 'msg' => '系统繁忙，请稍后再试'];
            }
            jobsModel::where('id', $jobs_id)->setInc('total_users');
            jobsModel::where('id', $jobs_id)->setInc('progress_total');
            return ['code' => 1, 'msg' => '参与成功', 'data' => $res->id];
        }
        if ((int)$progress->grant_status === 1) {
            return ['code' => 0, 'msg' => '您有正在进行中的任务，请先完成再参与'];
        }
        if ((int)$progress->grant_status === 2) {
            if ($activity->upgrade == 2) {
                if (!$next_jobs = jobsModel::getNextJobsInfoByActivity($progress->activity_id, $progress->jobs_id)) {
                    return ['code' => 0, 'msg' => '无法参与活动'];
                }
                if($next_jobs->id  != $jobs->id){
                    return ['code' => 0, 'msg' => '您已完成任务，请先完成再参与'];
                }
                $res = progressModel::userRegistrationParticipate($user_id, $jobs);
                if (!$res || !isset($res->id) || !$res->id) {
                    return ['code' => 0, 'msg' => '系统繁忙，请稍后再试'];
                }
                jobsModel::where('id', $jobs_id)->setInc('total_users');
                jobsModel::where('id', $jobs_id)->setInc('progress_total');
                return ['code' => 1, 'msg' => '参与成功', 'data' => $res->id];
            } else {
                return ['code' => 0, 'msg' => '您已完成任务，不可重复参加'];
            }
        }
        if ((int)$progress->grant_status === 3) {
            if ($activity->is_restart == 2) {
                $res = progressModel::userRegistrationParticipate($user_id, $jobs);
                if (!$res || !isset($res->id) || !$res->id) {
                    return ['code' => 0, 'msg' => '系统繁忙，请稍后再试'];
                }
                jobsModel::where('id', $jobs_id)->setInc('total_users');
                jobsModel::where('id', $jobs_id)->setInc('progress_total');
                return ['code' => 1, 'msg' => '参与成功', 'data' => $res->id];
            }
        }

        return ['code' => 0, 'msg' => '系统繁忙，请稍后再试'];
    }

    /*被邀请人点击邀请页码，显示助力详情*/
    public static function invitePeopleAssistDetails($progress_id){
        /*获取进度数据*/
        $progress = progressModel::where('id', $progress_id)->where('progress_type', 1)->find();
        if(!$progress){
            return ['code' => 0, 'msg' => '任务已结束，无法助力'];
        }

        /*获取任务详情*/
        if (!$jobs = jobsModel::getJobsInfo($progress->jobs_id)) {
            return ['code' => 0, 'msg' => '任务已结束，无法助力'];
        }

        /*获取任务详情*/
        if (!$activity = ActivityModel::getActivityInfo($jobs->activity_id)) {
            return ['code' => 0, 'msg' => '任务已结束，无法助力'];
        }

        $activity->self_reward = [
            'type' => $jobs->reward_method,
            'point' => $jobs->reward_method == 1 ? (int)$jobs->reward_point : 0,
            'youth' => $jobs->reward_method == 2 ? $jobs->youth_point : 0,
            'coupons' => MarketingCoupons::getAssociationCouponsOneArray($jobs->reward_coupons_id)
        ];
        $activity->inviter_reward = [
            'type' => $jobs->fu_reward_method,
            'point' => $jobs->fu_reward_method == 1 ? (int)$jobs->fu_reward_point : 0,
            'youth' => $jobs->fu_reward_method == 2 ? $jobs->fu_youth_point : 0,
            'coupons' => MarketingCoupons::getAssociationCouponsOneArray($jobs->fu_reward_coupons_id)
        ];
        return ['code' => 1, 'msg' => 'success', 'data' => $activity];
    }

    /*邀请人扫码助力*/
    public static function invitePeopleAssist($user_id, $progress_id){
        /*获取进度数据*/
        $progress = progressModel::where('id', $progress_id)->where('progress_type', 1)->find();
        if($progress->deadline_time < time()){
            return ['code' => 0, 'msg' => '任务已结束，无法助力'];
        }
        if($progress->grant_status == 2){
            return ['code' => 0, 'msg' => '任务已完成，无法助力'];
        }
        if($progress->grant_status == 3){
            return ['code' => 0, 'msg' => '任务已结束，无法助力'];
        }
        if($progress->user_id == $user_id){
            return ['code' => 0, 'msg' => '不能助力自己'];
        }
        /*获取任务详情*/
        if (!$jobs = jobsModel::getJobsInfo($progress->jobs_id)) {
            return ['code' => 0, 'msg' => '任务已结束，无法助力'];
        }
        /*获取任务详情*/
        if (!$activity = ActivityModel::getActivityInfo($progress->activity_id)) {
            return ['code' => 0, 'msg' => '任务已结束，无法助力'];
        }
        if($activity->start_time > time() || $activity->end_time < time()){
            return ['code' => 0, 'msg' => '任务已结束，无法助力'];
        }
        if($activity->grant_status > 2){
            return ['code' => 0, 'msg' => '任务已结束，无法助力'];
        }
        if($activity->grant_status == 2 && $activity->status_start_time){
            if($activity->status_start_time > time()){
                return ['code' => 0, 'msg' => '任务未开始，无法助力'];
            }
        }
        $res = progressModel::where('progress_id', $progress_id)->where('user_id', $user_id)
            ->where('progress_type', 2)->find();
        if($res){
            return ['code' => 0, 'msg' => '您已助力过了，无法重复助力'];
        }
        /*参与用户类型；2=新用户*/
        if($jobs->users_method == 2){
            if(!UsersModel::where('id', $user_id)->where('create_time', '>', (time() - 120))->find()){
                if(progressModel::where('user_id', $user_id)->find()){
                    return ['code' => 0, 'msg' => '您不是新用户，无法助力'];
                }
            }
        }
        Db::startTrans();
        if(!progressModel::userPeopleRegistrationParticipate($user_id, $progress)){
            DB::rollback();
            return ['code' => 0, 'msg' => '任务已结束，无法助力'];
        }
        /*领取优惠劵*/
        if(!self::distributeRewardsInviter($user_id, $jobs)){
            DB::rollback();
            return ['code' => 0, 'msg' => '任务已结束，无法助力'];
        }
        $user_total = progressModel::where('progress_id',$progress_id)->where('progress_type',2)->count();
        if($user_total >= $jobs->grant_total){
            if(!self::distributeRewardsSelf($progress->user_id, $jobs)){
                DB::rollback();
                return ['code' => 0, 'msg' => '任务已结束，无法助力'];
            }
            progressModel::setProgressCompletion($progress_id);
        }
        Db::commit();
        return  ['code' => 1, 'msg' => '助力成功, 您获得以下优惠卷', 'data' =>[
            'user_id' => $progress->user_id,
            'self_reward'   => [
                'type' => $jobs->reward_method,
                'point' => $jobs->reward_method == 1 ? (int)$jobs->reward_point : 0,
                'youth' => $jobs->reward_method == 2 ? $jobs->youth_point : 0,
                'coupons' => MarketingCoupons::getAssociationCouponsOneArray($jobs->reward_coupons_id)
            ],
            'inviter_reward' => [
                'type' => $jobs->fu_reward_method,
                'point' => $jobs->fu_reward_method == 1 ? (int)$jobs->fu_reward_point : 0,
                'youth' => $jobs->fu_reward_method == 2 ? $jobs->fu_youth_point : 0,
                'coupons' => MarketingCoupons::getAssociationCouponsOneArray($jobs->fu_reward_coupons_id)
            ]
        ]];
    }

    /*获取用户可参与的活动;首次进入页面*/
    public static function retrieveUsersFirstParticipateActivity($user_id, $circle_id = 0)
    {
        // 定义需要查询的字段
        $field = 'id,name,banner,slogan as sub_title,describe,guide,restart,upgrade,grant_status,share_img,share_title';
        // 初始化查询对象
        $query = ActivityModel::field($field)->where(function ($query) {
            $query->where('status', 1)->whereOr(function ($query) {
                $query->where('status', 2)->where('status_start_time', '<', time());
            });
        });
        // 构建复杂的查询条件，包括社团的授权方式和用户、圈子的关系
        $query->where(function ($query) use ($user_id, $circle_id) {
            $query->where('grant_method', 1);
            if($circle_id){
                $query->whereOr(function ($q) use ($circle_id, $user_id) {
                    $q->whereOr(function ($q) use ($circle_id) {
                        $q->where("grant_method", 2)->whereRaw("FIND_IN_SET('{$circle_id}', grant_agent_id)");
                    })->whereOr(function ($q) use ($user_id) {
                        $q->where("grant_method", 3)->whereRaw("FIND_IN_SET('{$user_id}', grant_users_id)");
                    });
                });
            } else {
                $query->whereOr(function ($q) use ($user_id) {
                    $q->where("grant_method", 3)->whereRaw("FIND_IN_SET('{$user_id}', grant_users_id)");
                });
            }
        });
        $query->where('start_time', '<', time())->where('end_time', '>', time());
        // 执行查询并分页
        $activity = $query->order('id', 'desc')->find();
        /*获取任务详情*/
        if (!$jobs = jobsModel::getJobsInfoByActivity($activity->id)) {
            return [];
        }
        $activity->deadline_time = 0;
        $activity->self_reward = [
            'type' => $jobs->reward_method,
            'point' => $jobs->reward_method == 1 ? (int)$jobs->reward_point : 0,
            'youth' => $jobs->reward_method == 2 ? $jobs->youth_point : 0,
            'coupons' => MarketingCoupons::getAssociationCouponsOneArray($jobs->reward_coupons_id)
        ];
        $activity->inviter_reward = [
            'type' => $jobs->fu_reward_method,
            'point' => $jobs->fu_reward_method == 1 ? (int)$jobs->fu_reward_point : 0,
            'youth' => $jobs->fu_reward_method == 2 ? $jobs->fu_youth_point : 0,
            'coupons' => MarketingCoupons::getAssociationCouponsOneArray($jobs->fu_reward_coupons_id)
        ];
        $activity->activity_status = 1;
        $activity->is_restart = (int)$activity->restart;
        $activity->is_upgrade = (int)$activity->upgrade;
        $activity->grant_status = 0;
        $activity->current_jobs_id = (int)$jobs->id;
        $activity->grant_total = (int)$jobs->grant_total;
        $activity->days_num = (int)$jobs->days_num;
        $activity->users_method = (int)$jobs->users_method;
        $activity->progress_id = 0;
        $activity->share_img = cdnurl($activity->share_img);
        $help_users_list = [];
        for ($i = 0; $i < $activity->grant_total; $i++) {
            $help_users_list[$i] = ['user_id' => 0, 'nickname' => '', 'avatar' => ''];
        }
        $activity->help_users_list = $help_users_list;
        return $activity;
    }

    /*获取用户可参与的活动*/
    public static function retrieveUsersParticipateActivity($user_id, $circle_id = 0)
    {
        // 定义需要查询的字段
        $field = 'id,name,banner,describe,guide,start_time,end_time,grant_method,grant_agent_id,grant_users_id,
        restart,upgrade,grant_status,status_start_time';

        // 初始化查询对象
        $query = ActivityModel::field($field)->where(function ($query) {
            $query->where('status', 1)->whereOr(function ($query) {
                $query->where('status', 2)->where('status_start_time', '<', time());
            });
        });
        // 构建复杂的查询条件，包括社团的授权方式和用户、圈子的关系
        $query->where(function ($query) use ($user_id, $circle_id) {
            $query->where('grant_method', 1);
            if($circle_id){
                $query->whereOr(function ($q) use ($circle_id, $user_id) {
                    $q->whereOr(function ($q) use ($circle_id) {
                        $q->where("grant_method", 2)->whereRaw("FIND_IN_SET('{$circle_id}', grant_agent_id)");
                    })->whereOr(function ($q) use ($user_id) {
                        $q->where("grant_method", 3)->whereRaw("FIND_IN_SET('{$user_id}', grant_users_id)");
                    });
                });
            } else {
                $query->whereOr(function ($q) use ($user_id) {
                    $q->where("grant_method", 3)->whereRaw("FIND_IN_SET('{$user_id}', grant_users_id)");
                });
            }
        });
        $query->where('start_time', '<', time())->where('end_time', '>', time());
        // 执行查询并分页
        $activity = $query->order('id', 'desc')->find();
        return $activity;
    }

    /*获取用户当前活动是否可参加*/
    public static function getUsersParticipateActivity($activity_id, $user_id, $circle_id)
    {
        // 定义需要查询的字段
        $field = 'id,name,slogan as sub_title,banner,describe,guide,start_time,end_time,grant_method,grant_agent_id,grant_users_id,
        restart,upgrade,grant_status,status_start_time,share_title,share_img';

        // 初始化查询对象
        $query = ActivityModel::field($field)->where('id', $activity_id)->where(function ($query) {
            $query->where('status', 1)->whereOr(function ($query) {
                $query->where('status', 2)->where('status_start_time', '<', time());
            });
        });
        // 构建复杂的查询条件，包括社团的授权方式和用户、圈子的关系
        $query->where(function ($query) use ($user_id, $circle_id) {
            $query->where('grant_method', 1);
            if($circle_id){
                $query->whereOr(function ($q) use ($circle_id, $user_id) {
                    $q->whereOr(function ($q) use ($circle_id) {
                        $q->where("grant_method", 2)->whereRaw("FIND_IN_SET('{$circle_id}', grant_agent_id)");
                    })->whereOr(function ($q) use ($user_id) {
                        $q->where("grant_method", 3)->whereRaw("FIND_IN_SET('{$user_id}', grant_users_id)");
                    });
                });
            } else {
                $query->whereOr(function ($q) use ($user_id) {
                    $q->where("grant_method", 3)->whereRaw("FIND_IN_SET('{$user_id}', grant_users_id)");
                });
            }
        });
        $query->where('start_time', '<', time())->where('end_time', '>', time());
        return $query->order('id', 'desc')->find();
    }

    /*发放被邀请人奖励*/
    public static function distributeRewardsInviter($user_id, $jobs)
    {
        switch ($jobs->fu_reward_method){
            case 1:
                UsersModel::increaseUserCurrency($user_id, (int)$jobs->fu_reward_point, 'score', '助力获取');
                break;
            case 2:
                UsersModel::increaseUserCurrency($user_id, (int)$jobs->fu_youth_point, 'youth_coin', '助力获取');
                break;
            case 3:
                if(!$reward_coupons_id = XypHelper::formatJsonStringToArray($jobs->fu_reward_coupons_id)){
                    return false;
                }

                foreach ($reward_coupons_id as $value){
                    $field = 'id,expiration_method,use_end_time,effective_days,type';
                    $coupon = MarketingCoupons::field($field)->where('id', $value['id'])->find();
                    $res = UsersMarketingCoupons::usersJobsReceiveCoupons($user_id, $coupon,2);
                }
                break;

        }
        return true;
    }

    /*发放邀请人奖励*/
    public static function distributeRewardsSelf($user_id, $jobs)
    {
        switch ($jobs->reward_method){
            case 1:
                UsersModel::increaseUserCurrency($user_id, (int)$jobs->reward_point, 'score', '助力获取');
                break;
            case 2:
                UsersModel::increaseUserCurrency($user_id, (int)$jobs->youth_point, 'youth_coin', '助力获取');
                break;
            case 3:
                if(!$reward_coupons_id = XypHelper::formatJsonStringToArray($jobs->reward_coupons_id)){
                    return false;
                }
                foreach ($reward_coupons_id as $value){
                    $field = 'id,expiration_method,use_end_time,effective_days,type';
                    $coupon = MarketingCoupons::field($field)->where('id', $value['id'])->find();
                    $res = UsersMarketingCoupons::usersJobsReceiveCoupons($user_id, $coupon,2);
                }
                break;
        }
        return true;
    }

    public static function helpList($user_id, $status = 0)
    {
        $field = 'id,id as progress_id,activity_id,jobs_id,grant_status,deadline_time';
        $query = progressModel::field($field)->where('user_id', $user_id)->where('progress_type', 1);
        if($status){
            $query->where('grant_status', $status);
        }
        $progress = $query->order('id desc')->paginate();
           if(!$progress->items()){
               return $progress;
           }
        foreach ($progress as $key => $value){
            $field = 'id,reward_method,reward_point,youth_point,reward_coupons_id,grant_total';
            $jobs = JobsModel::field($field)->where('id', $value['jobs_id'])->find();
            $value->self_reward = [
                'type' => $jobs->reward_method,
                'point' => $jobs->reward_method == 1 ? (int)$jobs->reward_point : 0,
                'youth' => $jobs->reward_method == 2 ? $jobs->youth_point : 0,
                'coupons' => MarketingCoupons::getAssociationCouponsOneArray($jobs->reward_coupons_id)
            ];
            $value->deadline_time = ($value->deadline_time - time());
            $value->grant_total = $jobs->grant_total;
            $value->difference = progressModel::getParticipateDifferenceUsers($value->id, $jobs->grant_total);
            $value->help_users_list = progressModel::getParticipateUsersList($value->id, $jobs->grant_total);
        }
        return $progress;
    }
}